import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/components/bigfontchoosebutton.dart';
import 'package:dio/dio.dart';
import 'package:wayofdressing/dio/ClothDio.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'dart:io';
import 'package:wayofdressing/category/clothcategory.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';

class AddClothScreen extends StatefulWidget {
  const AddClothScreen({super.key});

  @override
  State<AddClothScreen> createState() => _AddClothScreenState();
}

class _AddClothScreenState extends State<AddClothScreen> {
  int whoisactive1 = 1;
  int whoisactive2 = 1;

  List<String> categories = [];

  TextEditingController _purchaseLinkController = TextEditingController();
  TextEditingController _nameController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAdd = false;
    categories = clothSubCategories.keys.toList();
  }
  File? _image;

  Future getImage() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
  }
  void addCloth() async {
    String purchaseLink = _purchaseLinkController.text;
    String name = _nameController.text;
    List<String> categories = clothSubCategories.keys.toList();
    String activeCategory = categories[whoisactive1];
    String activeSubCategory =
        clothSubCategories[activeCategory]![whoisactive2];

    // 准备衣物数据
    Map<String, dynamic> clothData = {
      'clothName': name,
      'purchaseLink': purchaseLink,
      'category': activeCategory,
      'subcategory': activeSubCategory,
    };
    if (name == '' || purchaseLink == '') {
      ShowDialog.showErrorAndDetail(context, '输入不能为空!');
      return;
    }

    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int userId = prefs.getInt('id') ?? 0;
      Response<dynamic> response = await addClothByUserId(
          dio: dio,
          userId: userId,
          clothData: clothData,
          imagePath: _image?.path);

      dynamic responseData = response.data;

      if (responseData['success'] == true) {
        isAdd = true;
        ShowDialog.showCorrect(context);
      } else {
        ShowDialog.showError(context);
        throw Exception('添加失败');
      }
    } catch (e) {
      print('Error: $e');
      ShowDialog.showError(context);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _purchaseLinkController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 40.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Expanded(
                flex: 6,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Flexible(
                      child: Stack(
                        children: [
                          Container(
                            child: _image == null
                                ? const Icon(
                                    Icons.add_photo_alternate_outlined,
                                    size: 220,
                                  )
                                : Image.file(
                                    _image!,
                                    height: 300,
                                  ),
                          ),
                          if (_image != null)
                            Positioned(
                              right: 0,
                              bottom: 0,
                              child: IconButton(
                                icon: Icon(
                                  Icons.cancel_outlined,
                                  color: Colors.red,
                                  size: 36,
                                ),
                                onPressed: () {
                                  setState(() {
                                    _image = null;
                                  });
                                },
                              ),
                            ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(25), // 圆角半径
                            border: Border.all(
                              // 边框
                              color: Colors.black54, // 边框颜色
                              width: 2, // 边框宽度
                            ),
                          ),
                          child: TextButton(
                            child: Text(
                              '添加图片',
                              style: TextStyle(
                                  color: Colors.black54, fontSize: 30),
                            ),
                            onPressed: getImage,
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Expanded(
                child: Container(
                  margin: EdgeInsets.symmetric(vertical: 10),
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                        spreadRadius: 2, // 阴影扩展半径
                        blurRadius: 5, // 阴影模糊半径
                        offset: Offset(0, 5), // 阴影偏移量
                      ),
                    ],
                    borderRadius: BorderRadius.circular(25),
                    color: Colors.grey[200],
                  ),
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: clothSubCategories.length,
                    itemBuilder: (context, index) {
                      return BigFontChooseButton(
                        isActive: whoisactive1,
                        text: categories[index],
                        listNumber: index,
                        onPressed: () {
                          setState(() {
                            whoisactive1 = index;
                            whoisactive2 = 0;
                          });
                        },
                      );
                    },
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  margin: EdgeInsets.symmetric(vertical: 10),
                  height: 48,
                  decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                        spreadRadius: 2, // 阴影扩展半径
                        blurRadius: 5, // 阴影模糊半径
                        offset: Offset(0, 5), // 阴影偏移量
                      ),
                    ],
                    borderRadius: BorderRadius.circular(25),
                    color: Colors.grey[200],
                  ),
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: clothSubCategories[categories[whoisactive1]]
                        ?.length,
                    itemBuilder: (context, index) {
                      return BigFontChooseButton(
                        isActive: whoisactive2,
                        text: clothSubCategories[categories[whoisactive1]]![
                            index],
                        listNumber: index,
                        onPressed: () {
                          setState(() {
                            whoisactive2 = index;
                          });
                        },
                      );
                    },
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _nameController,
                        decoration: InputDecoration(
                          labelText: '衣服名称',
                          labelStyle:
                              TextStyle(fontSize: 20, color: Colors.grey),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(25.0),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(25.0),
                            borderSide:
                                BorderSide(width: 2, color: Colors.grey),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(25.0),
                            borderSide:
                                BorderSide(width: 2, color: Colors.black),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _purchaseLinkController,
                        decoration: InputDecoration(
                          labelText: '购买链接',
                          labelStyle:
                              TextStyle(fontSize: 20, color: Colors.grey),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(25.0),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(25.0),
                            borderSide:
                                BorderSide(width: 2, color: Colors.grey),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(25.0),
                            borderSide:
                                BorderSide(width: 2, color: Colors.black),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                flex: 2,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(25), // 圆角半径
                        border: Border.all(
                          // 边框
                          color: Colors.black54, // 边框颜色
                          width: 2, // 边框宽度
                        ),
                      ),
                      child: TextButton(
                        child: Text(
                          '添加',
                          style: TextStyle(color: Colors.black54, fontSize: 30),
                        ),
                        onPressed: addCloth,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
